package com.ishanggang.service;

import com.ishanggang.entity.JddjStore;
import com.ishanggang.entity.RetailerQuechaoJddj;
import com.ishanggang.entity.ShopQuechao;
import com.ishanggang.entity.ShopQuechaoJddj;
import com.ishanggang.entity.StoreMatchScoreVo;
import com.ishanggang.mapper.JddjStoreMapper;
import com.ishanggang.mapper.RetailerQuechaoJddjMapper;
import com.ishanggang.mapper.ShopQuechaoJddjMapper;
import com.ishanggang.mapper.ShopQuechaoMapper;
import com.ishanggang.util.DistanceUtil;
import com.ishanggang.util.GaoDeLatAndLngUtil;
import com.ishanggang.util.GeoHashUtil;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

@Service
public class BrandMatchJddjStoreService {

  private static final Logger logger = LoggerFactory.getLogger(BrandMatchJddjStoreService.class);
  @Resource
  private JddjStoreMapper jddjStoreMapper;
  @Resource
  private ShopQuechaoMapper shopQuechaoMapper;
  @Resource
  private RetailerQuechaoJddjMapper retailerQuechaoJddjMapper;
  @Resource
  private ShopQuechaoJddjMapper shopQuechaoJddjMapper;
  @Resource
  private GeoHashUtil geoHashUtil;
  public static final String JDDJ_STORE_GEOHASH_KEY = "JDDJ_STORE_GEOHASH_KEY";
  public static final Integer DISTANCE = 2;
  private static final Double MAX_JUDGE_DISTANCE = 1.0;
  public static final Integer totalCount = 300;
  // 距离每增加 100 M,匹配度得分扣 N 目前设置为5
  private static final Integer DISTANCE_PER_HUNDRED_M_SCORE = 5;
  // ka 名称每匹配一个字,加 5 分
  private static final Integer KA_NAME_PER_WORD_MATCH_SCORE = 5;
  // 门店 名称每匹配一个字,加 3 分
  private static final Integer STORE_NAME_PER_WORD_MATCH_SCORE = 3;
  // 门店 地址每匹配一个字,加 3 分
  private static final Integer STORE_ADDRESS_PER_WORD_MATCH_SCORE = 3;

  /**
   * 查询经纬度附近的京东到家门店列表
   * @param brandShopLng
   * @param brandShopLat
   */
  public void queryNearByJddjShopList(double brandShopLng, double brandShopLat) {
    GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = this.geoHashUtil.redisNearByXY(
            JDDJ_STORE_GEOHASH_KEY, brandShopLng,
            brandShopLat, DISTANCE, totalCount);
    int i = 0;
    for (GeoResult<RedisGeoCommands.GeoLocation<String>> item : geoResults.getContent()) {
      ++i;
      JddjStore jddjStore2 = this.jddjStoreMapper.selectById(
              Long.parseLong(String.valueOf(item.getContent().getName())));
      logger.info("{}", jddjStore2);
    }
  }

  public void initRedisJddjStoreInfo() {
    Long maxId = this.jddjStoreMapper.selectMaxId();
    Long i = 1L;
    while (true) {
      this.initRedisJddjStoreItem(i);
      if (i > maxId) {
        break;
      }
      i++;
    }
  }

  public void updateRetailerQuechaoGroupId() {
    List<RetailerQuechaoJddj> retailerQuechaoJddjList = this.retailerQuechaoJddjMapper.queryAllRetailerQuechaoJddj();
    for (RetailerQuechaoJddj retailerQuechaoJddj : retailerQuechaoJddjList) {
      Long jddjRetailerGroupId = this.jddjStoreMapper.selectGroupRetailerIdByRetailerId(
          retailerQuechaoJddj.getJddjRetailerId());
      if (jddjRetailerGroupId == null || jddjRetailerGroupId <= 0L) {
        continue;
      }
      this.retailerQuechaoJddjMapper.updateRetailerGroupId(String.valueOf(jddjRetailerGroupId),
          retailerQuechaoJddj.getJddjRetailerId());
    }
  }

  public void initRedisJddjStoreItem(Long id) {
    JddjStore jddjStore = this.jddjStoreMapper.selectById(id);
    if (jddjStore != null) {
      try {
        this.geoHashUtil.redisGeoAdd(JDDJ_STORE_GEOHASH_KEY,
            Double.parseDouble(jddjStore.getLongitude()),
            Double.parseDouble(jddjStore.getLatitude()), String.valueOf(jddjStore.getId()));
        logger.info("=================={}", jddjStore.getId());
      } catch (Exception e) {
        logger.error("转化异常", e);
      }
    }
  }

  public void buildQueChaoJDDJStoreId() {
    Long maxId = this.shopQuechaoMapper.selectMaxId();
    Map<String, List<String>> jddjRetailerId_quechaoRetailerNameListMap = this.buildJddjRetailerId_quechaoRetailerNameListMap();
    Map<String, List<String>> jddjGroupRetailerId_quechaoRetailerNameListMap = this.buildJddjGroupRetailerId_quechaoRetailerNameListMap();
    Map<String, List<String>> quechaoId_JddjRetailerIdListMap = this.quechaoId_JddjRetailerIdListMap();
    Long i = 1L;
    while (true) {
      this.buildQueChaoJDDJStoreIdItem(i, jddjRetailerId_quechaoRetailerNameListMap,
          jddjGroupRetailerId_quechaoRetailerNameListMap, quechaoId_JddjRetailerIdListMap);
      if (i > maxId) {
        break;
      }
      i++;
    }
  }

  public void updateShopLongLatAddressDistance() {
    // 取最大id
    Long maxId = this.shopQuechaoMapper.selectMaxId();
    Long i = 1L;
    while (true) {
      try {
        ShopQuechao shopQuechao = this.shopQuechaoMapper.selectById(i);
        if (shopQuechao != null && !StringUtils.isEmpty(shopQuechao.getAddress())) {
          Map<String, String> queChaoBaiduLatAndLngMap = GaoDeLatAndLngUtil.addressToLngAndLag(
              (String) shopQuechao.getAddress());
          if (!CollectionUtils.isEmpty(queChaoBaiduLatAndLngMap)) {
            double longLatAddressDistance = DistanceUtil.distance(
                (double) Double.parseDouble((String) queChaoBaiduLatAndLngMap.get("lng")),
                (double) Double.parseDouble((String) queChaoBaiduLatAndLngMap.get("lat")),
                (double) Double.parseDouble(String.valueOf(shopQuechao.getLng())),
                (double) Double.parseDouble(String.valueOf(shopQuechao.getLat())));
            this.shopQuechaoMapper.updateShopLongLatAddressDistance(i, longLatAddressDistance);
            logger.info("门店id:{},门店名称:{}--距离偏差值为{}m", shopQuechao.getId(), shopQuechao.getName(),
                longLatAddressDistance);
          } else {
            this.shopQuechaoMapper.updateShopLongLatAddressDistance(i, Double.parseDouble("-1"));
            logger.error("门店id:{},门店名称:{}--经纬度查询不合法{}", shopQuechao.getId(), shopQuechao.getName(),
                queChaoBaiduLatAndLngMap);
          }
        }
      } catch (Exception e) {
        logger.error("门店经纬度与地址不准统计，门店id:{}", i, e);
      }
      if (i > maxId) {
        break;
      }
      i++;
    }
  }


  public void updateShopLongLat() {
    // 取最大id
    Long maxId = this.shopQuechaoMapper.selectMaxId();
    Long i = 1L;
    while (true) {
      try {
        ShopQuechao shopQuechao = this.shopQuechaoMapper.selectById(i);
        if (shopQuechao != null && !StringUtils.isEmpty(shopQuechao.getAddress())) {
          Map<String, String> queChaoBaiduLatAndLngMap = GaoDeLatAndLngUtil.addressToLngAndLag(
                  (String) shopQuechao.getAddress());
          if (!CollectionUtils.isEmpty(queChaoBaiduLatAndLngMap)) {
            this.shopQuechaoMapper.updateShopLongLat(i, Double.parseDouble((String) queChaoBaiduLatAndLngMap.get("lng")), Double.parseDouble((String) queChaoBaiduLatAndLngMap.get("lat")));
            logger.info("门店id:{},门店名称:{}--距离偏差值为{}m", shopQuechao.getId(), shopQuechao.getName(),
                    1);
          } else {
//            this.shopQuechaoMapper.updateShopLongLatAddressDistance(i, Double.parseDouble("-1"));
            logger.error("门店id:{},门店名称:{}--经纬度查询不合法{}", shopQuechao.getId(), shopQuechao.getName(),
                    queChaoBaiduLatAndLngMap);
          }
        }
      } catch (Exception e) {
        logger.error("门店经纬度与地址不准统计，门店id:{}", i, e);
      }
      if (i > maxId) {
        break;
      }
      i++;
    }
  }




  private Map<String, List<String>> buildJddjRetailerId_quechaoRetailerNameListMap() {
    List<RetailerQuechaoJddj> retailerQuechaoJddjList = this.retailerQuechaoJddjMapper.queryAllRetailerQuechaoJddj();
    HashMap<String, List<String>> jddjRetailerId_quechaoRetailerNameListMap = new HashMap<String, List<String>>();
    for (RetailerQuechaoJddj retailerQuechaoJddj : retailerQuechaoJddjList) {
      ArrayList<String> quechaoRetailerNameList = (ArrayList<String>) jddjRetailerId_quechaoRetailerNameListMap.get(
          retailerQuechaoJddj.getJddjRetailerId());
      if (CollectionUtils.isEmpty(quechaoRetailerNameList)) {
        quechaoRetailerNameList = new ArrayList<String>();
      }
      quechaoRetailerNameList.add(retailerQuechaoJddj.getQuechaoRetailer());
      jddjRetailerId_quechaoRetailerNameListMap.put(retailerQuechaoJddj.getJddjRetailerId(),
          quechaoRetailerNameList);
    }
    return jddjRetailerId_quechaoRetailerNameListMap;
  }

  private Map<String, List<String>> buildJddjGroupRetailerId_quechaoRetailerNameListMap() {
    List<RetailerQuechaoJddj> retailerQuechaoJddjList = this.retailerQuechaoJddjMapper.queryAllRetailerQuechaoJddj();
    HashMap<String, List<String>> jddjGroupRetailerId_quechaoRetailerNameListMap = new HashMap<String, List<String>>();
    for (RetailerQuechaoJddj retailerQuechaoJddj : retailerQuechaoJddjList) {
      ArrayList<String> quechaoRetailerNameList = (ArrayList<String>) jddjGroupRetailerId_quechaoRetailerNameListMap.get(
          retailerQuechaoJddj.getJddjRetailerGroupId());
      if (CollectionUtils.isEmpty(quechaoRetailerNameList)) {
        quechaoRetailerNameList = new ArrayList<String>();
      }
      quechaoRetailerNameList.add(retailerQuechaoJddj.getQuechaoRetailer());
      jddjGroupRetailerId_quechaoRetailerNameListMap.put(
          retailerQuechaoJddj.getJddjRetailerGroupId(), quechaoRetailerNameList);
    }
    return jddjGroupRetailerId_quechaoRetailerNameListMap;
  }

  private Map<String, List<String>> quechaoId_JddjRetailerIdListMap() {
    List<RetailerQuechaoJddj> retailerQuechaoJddjList = this.retailerQuechaoJddjMapper.queryAllRetailerQuechaoJddj();
    HashMap<String, List<String>> quechaoRetailerName_jddjRetailerIdListMap = new HashMap<String, List<String>>();
    for (RetailerQuechaoJddj retailerQuechaoJddj : retailerQuechaoJddjList) {
      ArrayList<String> jddjRetailerIdList = (ArrayList<String>) quechaoRetailerName_jddjRetailerIdListMap.get(
          retailerQuechaoJddj.getQuechaoRetailer());
      if (CollectionUtils.isEmpty(jddjRetailerIdList)) {
        jddjRetailerIdList = new ArrayList<String>();
      }
      jddjRetailerIdList.add(retailerQuechaoJddj.getJddjRetailerId());
      quechaoRetailerName_jddjRetailerIdListMap.put(retailerQuechaoJddj.getQuechaoRetailer(),
          jddjRetailerIdList);
    }
    return quechaoRetailerName_jddjRetailerIdListMap;
  }

  /*
   * WARNING - void declaration
   */
  public void buildQueChaoJDDJStoreIdItem(Long id,
      Map<String, List<String>> jddjRetailerId_quechaoRetailerNameListMap,
      Map<String, List<String>> jddjGroupRetailerId_quechaoRetailerNameListMap,
      Map<String, List<String>> quechaoId_JddjRetailerIdListMap) {
    if (jddjRetailerId_quechaoRetailerNameListMap == null) {
      jddjRetailerId_quechaoRetailerNameListMap = this.buildJddjRetailerId_quechaoRetailerNameListMap();
    }
    if (jddjGroupRetailerId_quechaoRetailerNameListMap == null) {
      jddjGroupRetailerId_quechaoRetailerNameListMap = this.buildJddjGroupRetailerId_quechaoRetailerNameListMap();
    }
    if (quechaoId_JddjRetailerIdListMap == null) {
      quechaoId_JddjRetailerIdListMap = this.quechaoId_JddjRetailerIdListMap();
    }
    ShopQuechao shopQuechao = this.shopQuechaoMapper.selectById(id);
    Map queChaoBaiduLatAndLngMap = null;
    if (shopQuechao != null) {
      logger.info("============={}", shopQuechao);
      try {
        JddjStore jddjStore;
        double realDistance;
        // 品牌门店经纬度
        double brandShopLng = shopQuechao.getLng();
        double brandShopLat = shopQuechao.getLat();
        if (shopQuechao.getLongLatAddressDistance() != null
            && shopQuechao.getLongLatAddressDistance() > 600) {
          // 品牌提供的经纬度和地址相差600米，则认为品牌提供的经纬度不准，以地址解析经纬度为准
          queChaoBaiduLatAndLngMap = GaoDeLatAndLngUtil.addressToLngAndLag(
              (String) shopQuechao.getAddress());
          if(!CollectionUtils.isEmpty(queChaoBaiduLatAndLngMap)){
            brandShopLng =(double) Double.parseDouble((String) queChaoBaiduLatAndLngMap.get("lng"));
            brandShopLat = (double) Double.parseDouble((String) queChaoBaiduLatAndLngMap.get("lat"));
          }
        }
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = this.geoHashUtil.redisNearByXY(
            JDDJ_STORE_GEOHASH_KEY, brandShopLng,
            brandShopLat, DISTANCE, totalCount);
        int i = 0;
        for (GeoResult<RedisGeoCommands.GeoLocation<String>> item : geoResults.getContent()) {
          ++i;
          JddjStore jddjStore2 = this.jddjStoreMapper.selectById(
              Long.parseLong(String.valueOf(item.getContent().getName())));

          // 判断子公司是否匹配-匹配则认为 位置2KM附近 & 公司符合
          List<String> list = jddjRetailerId_quechaoRetailerNameListMap.get(
              String.valueOf(jddjStore2.getVenderId()));
          if (CollectionUtils.isEmpty(list) || !list.contains(shopQuechao.getKa())) {
            continue;
          }

          if (item.getDistance().getValue() > MAX_JUDGE_DISTANCE) {
            if (queChaoBaiduLatAndLngMap == null) {
              queChaoBaiduLatAndLngMap = GaoDeLatAndLngUtil.addressToLngAndLag(
                  (String) shopQuechao.getAddress());
            }
            Map jdShopBaiduLatAndLngMap = GaoDeLatAndLngUtil.addressToLngAndLag(
                (String) jddjStore2.getAddress());
            if (!CollectionUtils.isEmpty(queChaoBaiduLatAndLngMap) && !CollectionUtils.isEmpty(
                jdShopBaiduLatAndLngMap)) {
              double realDistance11 = DistanceUtil.distance(
                  (double) Double.parseDouble((String) queChaoBaiduLatAndLngMap.get("lng")),
                  (double) Double.parseDouble((String) queChaoBaiduLatAndLngMap.get("lat")),
                  (double) Double.parseDouble((String) jdShopBaiduLatAndLngMap.get("lng")),
                  (double) Double.parseDouble((String) jdShopBaiduLatAndLngMap.get("lat")));
              if (realDistance11 > MAX_JUDGE_DISTANCE * 1000.0) {
                logger.error("精准11地址解析距离大于{}KM,排除-雀巢门店名称{},jddjStoreId:{}", MAX_JUDGE_DISTANCE,
                    jddjStore2.getShopName(), jddjStore2.getId());
                continue;
              }
            }
          }
          logger.info("精准-11匹配商家{},jddjStoreId:{}", (Object) shopQuechao.getKa(),
              (Object) jddjStore2.getId());
          StoreMatchScoreVo storeMatchScoreVo = buildStoreMatchScore(shopQuechao, jddjStore2, 11,
              item.getDistance().getValue());
          this.buildShopQuechaoJddj(shopQuechao, jddjStore2, 11, item.getDistance().getValue(), i,
              storeMatchScoreVo.getMatchScore(), storeMatchScoreVo.getMatchScoreReason());
          return;
        }
        List<String> jddjRetailerIdList = quechaoId_JddjRetailerIdListMap.get(shopQuechao.getKa());
        if (!CollectionUtils.isEmpty(jddjRetailerIdList)) {
          List<Long> nearbyDjStoreIdList = this.jddjStoreMapper.selectNearbyStoreId(
              String.valueOf(shopQuechao.getLng()), String.valueOf(shopQuechao.getLat()),
              jddjRetailerIdList);
          int i2 = 0;
          for (Long l : nearbyDjStoreIdList) {
            List<String> quechaoRetailerNameList;
            ++i2;
            jddjStore = this.jddjStoreMapper.selectById(l);
            realDistance = DistanceUtil.distance(
                (double) Double.parseDouble(jddjStore.getLongitude()),
                (double) Double.parseDouble(jddjStore.getLatitude()), (double) shopQuechao.getLng(),
                (double) shopQuechao.getLat());
            if (realDistance > (double) (DISTANCE * 1000) || CollectionUtils.isEmpty(
                quechaoRetailerNameList = jddjRetailerId_quechaoRetailerNameListMap.get(
                    String.valueOf(jddjStore.getVenderId())))
                || !quechaoRetailerNameList.contains(
                shopQuechao.getKa())) {
              continue;
            }
            if (realDistance > MAX_JUDGE_DISTANCE * 1000.0) {
              if (queChaoBaiduLatAndLngMap == null) {
                queChaoBaiduLatAndLngMap = GaoDeLatAndLngUtil.addressToLngAndLag(
                    (String) shopQuechao.getAddress());
              }
              Map jdShopBaiduLatAndLngMap = GaoDeLatAndLngUtil.addressToLngAndLag(
                  (String) jddjStore.getAddress());
              if (!CollectionUtils.isEmpty(queChaoBaiduLatAndLngMap) && !CollectionUtils.isEmpty(
                  jdShopBaiduLatAndLngMap) && (DistanceUtil.distance(
                  (double) Double.parseDouble((String) queChaoBaiduLatAndLngMap.get("lng")),
                  (double) Double.parseDouble((String) queChaoBaiduLatAndLngMap.get("lat")),
                  (double) Double.parseDouble((String) jdShopBaiduLatAndLngMap.get("lng")),
                  (double) Double.parseDouble((String) jdShopBaiduLatAndLngMap.get("lat"))))
                  > MAX_JUDGE_DISTANCE * 1000.0) {
                logger.error("精准12地址解析距离大于{}KM,排除-雀巢门店名称{},jddjStoreId:{}", MAX_JUDGE_DISTANCE,
                    jddjStore.getShopName(), jddjStore.getId());
                continue;
              }
            }
            logger.info("精准--12匹配商家{},jddjStoreId:{}", (Object) shopQuechao.getKa(),
                (Object) jddjStore.getId());
            StoreMatchScoreVo storeMatchScoreVo = buildStoreMatchScore(shopQuechao, jddjStore, 12,
                realDistance / 1000.0);
            this.buildShopQuechaoJddj(shopQuechao, jddjStore, 12, realDistance / 1000.0, i2,
                storeMatchScoreVo.getMatchScore(), storeMatchScoreVo.getMatchScoreReason());
            return;
          }
        }
        int i3 = 0;
        for (GeoResult<RedisGeoCommands.GeoLocation<String>> geoResult : geoResults.getContent()) {
          ++i3;
          Long l = Long.parseLong(String.valueOf(geoResult.getContent().getName()));
          jddjStore = this.jddjStoreMapper.selectById(l);
          List<String> quechaoRetailerNameList = jddjGroupRetailerId_quechaoRetailerNameListMap.get(
              String.valueOf(jddjStore.getVenderGroupId()));
          if (CollectionUtils.isEmpty(quechaoRetailerNameList)
              || !quechaoRetailerNameList.contains(
              shopQuechao.getKa())) {
            continue;
          }
          if (geoResult.getDistance().getValue() > MAX_JUDGE_DISTANCE) {
            if (queChaoBaiduLatAndLngMap == null) {
              queChaoBaiduLatAndLngMap = GaoDeLatAndLngUtil.addressToLngAndLag(
                  (String) shopQuechao.getAddress());
            }
            Map jdShopBaiduLatAndLngMap = GaoDeLatAndLngUtil.addressToLngAndLag(
                (String) jddjStore.getAddress());
            if (!CollectionUtils.isEmpty(queChaoBaiduLatAndLngMap) && !CollectionUtils.isEmpty(
                jdShopBaiduLatAndLngMap) && (DistanceUtil.distance(
                (double) Double.parseDouble((String) queChaoBaiduLatAndLngMap.get("lng")),
                (double) Double.parseDouble((String) queChaoBaiduLatAndLngMap.get("lat")),
                (double) Double.parseDouble((String) jdShopBaiduLatAndLngMap.get("lng")),
                (double) Double.parseDouble((String) jdShopBaiduLatAndLngMap.get("lat"))))
                > MAX_JUDGE_DISTANCE * 1000.0) {
              logger.error("精准13地址解析距离大于{}KM,排除-雀巢门店名称{},jddjStoreId:{}", MAX_JUDGE_DISTANCE,
                  jddjStore.getShopName(), jddjStore.getId());
              continue;
            }
          }
          logger.info("精准---13匹配商家集团{},jddjStoreId:{}", (Object) shopQuechao.getKa(),
              (Object) jddjStore.getId());
          StoreMatchScoreVo storeMatchScoreVo = buildStoreMatchScore(shopQuechao, jddjStore, 13,
              geoResult.getDistance().getValue());
          this.buildShopQuechaoJddj(shopQuechao, jddjStore, 13, geoResult.getDistance().getValue(),
              i3, storeMatchScoreVo.getMatchScore(), storeMatchScoreVo.getMatchScoreReason());
          return;
        }
        int j = 0;
        for (GeoResult<RedisGeoCommands.GeoLocation<String>> geoResult : geoResults.getContent()) {
          ++j;
          Long jddjStoreId = Long.parseLong(String.valueOf(geoResult.getContent().getName()));
          JddjStore jddjStore3 = this.jddjStoreMapper.selectById(jddjStoreId);
          if (jddjStore3 == null || Strings.isBlank(jddjStore3.getVenderGroupName())
              || !jddjStore3.getVenderGroupName().equals(shopQuechao.getKa())
              && !jddjStore3.getVenderGroupName().contains(shopQuechao.getKa())) {
            continue;
          }
          if (geoResult.getDistance().getValue() > MAX_JUDGE_DISTANCE) {
            if (queChaoBaiduLatAndLngMap == null) {
              queChaoBaiduLatAndLngMap = GaoDeLatAndLngUtil.addressToLngAndLag(
                  (String) shopQuechao.getAddress());
            }
            Map jdShopBaiduLatAndLngMap = GaoDeLatAndLngUtil.addressToLngAndLag(
                (String) jddjStore3.getAddress());
            if (!CollectionUtils.isEmpty(queChaoBaiduLatAndLngMap) && !CollectionUtils.isEmpty(
                jdShopBaiduLatAndLngMap)) {
              double distinct02 = DistanceUtil.distance(
                  (double) Double.parseDouble((String) queChaoBaiduLatAndLngMap.get("lng")),
                  (double) Double.parseDouble((String) queChaoBaiduLatAndLngMap.get("lat")),
                  (double) Double.parseDouble((String) jdShopBaiduLatAndLngMap.get("lng")),
                  (double) Double.parseDouble((String) jdShopBaiduLatAndLngMap.get("lat")));
              if (distinct02 > MAX_JUDGE_DISTANCE * 1000.0) {
                logger.error("模糊匹配商家-地址解析距离大于{}KM,排除-雀巢门店名称{},jddjStoreId:{}", MAX_JUDGE_DISTANCE,
                    jddjStore3.getShopName(), jddjStore3.getId());
                continue;
              }
            }
          }
          logger.info("模糊匹配商家{},jddjStoreId:{}", (Object) shopQuechao.getKa(),
              (Object) jddjStore3.getId());
          StoreMatchScoreVo storeMatchScoreVo = buildStoreMatchScore(shopQuechao, jddjStore3, 2,
              geoResult.getDistance().getValue());
          this.buildShopQuechaoJddj(shopQuechao, jddjStore3, 2, geoResult.getDistance().getValue(),
              j, storeMatchScoreVo.getMatchScore(), storeMatchScoreVo.getMatchScoreReason());
          return;
        }
        boolean bl = false;
        for (GeoResult<RedisGeoCommands.GeoLocation<String>> item : geoResults.getContent()) {
          int var12_25 = 0;
          ++var12_25;
          Long jddjStoreId = Long.parseLong(String.valueOf(item.getContent().getName()));
          JddjStore jddjStore4 = this.jddjStoreMapper.selectById(jddjStoreId);
          if (jddjStore4 == null || Strings.isBlank(jddjStore4.getVenderGroupName())) {
            continue;
          }
          logger.info("距离匹配商家{},jddjStoreId:{}", (Object) shopQuechao.getKa(),
              (Object) jddjStore4.getId());
          StoreMatchScoreVo storeMatchScoreVo = buildStoreMatchScore(shopQuechao, jddjStore4, 2,
              item.getDistance().getValue());
          this.buildShopQuechaoJddj(shopQuechao, jddjStore4, 3, item.getDistance().getValue(),
              (int) var12_25, storeMatchScoreVo.getMatchScore(),
              storeMatchScoreVo.getMatchScoreReason());
          return;
        }
      } catch (Exception e) {
        logger.error("转化异常", e);
      }
    }
  }

  public void queChaoJDDJStoreMatchProcessDetail(Long id,
      Map<String, List<String>> jddjRetailerId_quechaoRetailerNameListMap,
      Map<String, List<String>> quechaoId_JddjRetailerIdListMap) {
    ShopQuechao shopQuechao;
    if (jddjRetailerId_quechaoRetailerNameListMap == null) {
      jddjRetailerId_quechaoRetailerNameListMap = this.buildJddjRetailerId_quechaoRetailerNameListMap();
    }
    if (quechaoId_JddjRetailerIdListMap == null) {
      quechaoId_JddjRetailerIdListMap = this.quechaoId_JddjRetailerIdListMap();
    }
    if ((shopQuechao = this.shopQuechaoMapper.selectById(id)) != null) {
      logger.error("============={}", (Object) shopQuechao);
      try {
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = this.geoHashUtil.redisNearByXY(
            JDDJ_STORE_GEOHASH_KEY, shopQuechao.getLng().doubleValue(),
            shopQuechao.getLat().doubleValue(), DISTANCE, totalCount);
        int i = 0;
        for (GeoResult<RedisGeoCommands.GeoLocation<String>> item : geoResults.getContent()) {
          Long jddjStoreId = Long.parseLong(String.valueOf(item.getContent().getName()));
          JddjStore jddjStore = this.jddjStoreMapper.selectById(jddjStoreId);
          logger.error("距离排序1{}----{}附近{}KM的门店{}", ++i, shopQuechao.getName(),
              item.getDistance().getValue(), jddjStore);
          List<String> quechaoRetailerNameList = jddjRetailerId_quechaoRetailerNameListMap.get(
              String.valueOf(jddjStore.getVenderId()));
          if (CollectionUtils.isEmpty(quechaoRetailerNameList)
              || !quechaoRetailerNameList.contains(
              shopQuechao.getKa())) {
            continue;
          }
          logger.error("====精准匹配商家{},jddjStoreId:{}", (Object) shopQuechao.getKa(),
              (Object) jddjStore.getId());
        }
        List<String> jddjRetailerIdList = quechaoId_JddjRetailerIdListMap.get(shopQuechao.getKa());
        if (!CollectionUtils.isEmpty(jddjRetailerIdList)) {
          List<Long> nearbyDjStoreIdList = this.jddjStoreMapper.selectNearbyStoreId(
              String.valueOf(shopQuechao.getLng()), String.valueOf(shopQuechao.getLat()),
              jddjRetailerIdList);
          int i2 = 0;
          for (Long nearbyDjStoreId : nearbyDjStoreIdList) {
            ++i2;
            JddjStore jddjStore = this.jddjStoreMapper.selectById(nearbyDjStoreId);
            double realDistance = DistanceUtil.distance(
                (double) Double.valueOf(jddjStore.getLongitude()),
                (double) Double.valueOf(jddjStore.getLatitude()), (double) shopQuechao.getLng(),
                (double) shopQuechao.getLat());
            if (realDistance > (double) (DISTANCE * 1000)) {
              logger.error("精准2距离大于排除-门店名称{},jddjStoreId:{}", (Object) jddjStore.getShopName(),
                  (Object) jddjStore.getId());
              continue;
            }
            logger.error("MYSQL距离排序{}----{}附近{}KM的门店{}", i2, shopQuechao.getName(),
                realDistance / 1000.0, jddjStore);
            List<String> quechaoRetailerNameList = jddjRetailerId_quechaoRetailerNameListMap.get(
                String.valueOf(jddjStore.getVenderId()));
            if (CollectionUtils.isEmpty(quechaoRetailerNameList)
                || !quechaoRetailerNameList.contains(shopQuechao.getKa())) {
              continue;
            }
            logger.info("精准2匹配商家{},jddjStoreId:{}", (Object) shopQuechao.getKa(),
                (Object) jddjStore.getId());
            return;
          }
        }
        for (GeoResult<RedisGeoCommands.GeoLocation<String>> item : geoResults.getContent()) {
          Long jddjStoreId = Long.parseLong(String.valueOf(item.getContent().getName()));
          JddjStore jddjStore = this.jddjStoreMapper.selectById(jddjStoreId);
          if (!jddjStore.getVenderGroupName().equals(shopQuechao.getKa())
              && !jddjStore.getVenderGroupName().contains(shopQuechao.getKa())) {
            continue;
          }
          logger.error("====模糊匹配商家{},jddjStoreId:{}", (Object) shopQuechao.getKa(),
              (Object) jddjStore.getId());
        }
        logger.error("====未匹配{},jddjStoreId:{}", (Object) shopQuechao.getKa(),
            ((RedisGeoCommands.GeoLocation) geoResults.getContent().get(0).getContent()).getName());
      } catch (Exception e) {
        logger.error("转化异常", e);
      }
    }
  }

  private void buildShopQuechaoJddj(ShopQuechao shopQuechao, JddjStore jddjStore, Integer matchType,
      double distance, Integer matchNum, Integer matchScore, String matchScoreReason) {
    ShopQuechaoJddj oldShopQuechaoJddj = this.shopQuechaoJddjMapper.queryShopQuechaoJddj(
        shopQuechao.getId(), shopQuechao.getShopId());
    if (oldShopQuechaoJddj == null) {
      this.shopQuechaoJddjMapper.insertShopQuechaoJddj(jddjStore.getShopId(), matchType,
          shopQuechao.getId(), shopQuechao.getShopId(), Double.valueOf(distance), matchNum,
          matchScore, matchScoreReason);
    } else {
      this.shopQuechaoJddjMapper.updateShopQuechaoJddjById(oldShopQuechaoJddj.getId(),
          jddjStore.getShopId(), matchType, Double.valueOf(distance), matchNum, matchScore,
          matchScoreReason);
    }
  }

  /**
   * 构建匹配逻辑得分
   *
   * @param shopQuechao 品牌侧门店
   * @param jddjStore   京东到家侧门店
   * @return 得分明细
   */
  private StoreMatchScoreVo buildStoreMatchScore(ShopQuechao shopQuechao, JddjStore jddjStore,
      Integer matchType, double distance) {
    // 1.商家和门店匹配距离 总分50分  每差100米 减 n分，最低0分.
    StringBuilder builder = new StringBuilder();
    BigDecimal b1 = new BigDecimal(distance);
    int distanceScore =
        50 - b1.multiply(BigDecimal.valueOf(10)).intValue() * DISTANCE_PER_HUNDRED_M_SCORE;
    builder.append("相距距离满分50分-真实距离：" + distance + "KM，每100米减" + DISTANCE_PER_HUNDRED_M_SCORE + ",得"
        + distanceScore + "分;---");
    // 2.子公司名称精准匹配 总分40分， 匹配 40分 不匹配 0分.
    String brandKaName = shopQuechao.getKa();
    String venderName = jddjStore.getVenderName();
    StringBuilder matchKaName = new StringBuilder();
    if (!StringUtils.isEmpty(brandKaName)) {
      for (int i = 0; i < brandKaName.length(); i++) {
        if (venderName.contains(String.valueOf(brandKaName.charAt(i)))) {
          matchKaName.append(brandKaName.charAt(i));
        }
      }
    }
    int kaNameMatchScore = matchKaName.length() * KA_NAME_PER_WORD_MATCH_SCORE;
    builder.append(
        "子公司名称匹配满分40分-到家侧零售子公司名称：" + jddjStore.getVenderName() + "，品牌侧零售子公司名称" + shopQuechao.getKa()
            + ",匹配文字"
            + matchKaName + "；得分：" + kaNameMatchScore + "分;---");
    // 3.商家集团匹配 总分20分 匹配20分 不匹配 0分.
    int venderGroupMatchScore = 0;
    if (matchType != null && (matchType == 11 || matchType == 12 || matchType == 13)) {
      venderGroupMatchScore = 20;
    } else if (matchType == 2) {
      venderGroupMatchScore = 20;
    }
    builder.append(
        "商家匹配满分20分：得分：" + venderGroupMatchScore + "分;---");
    // 4.门店名称 分词匹配 每匹配上一个字  加5分 上限 30分.
    String storeName = shopQuechao.getName();
    String jddjShopName = jddjStore.getShopName();
    StringBuilder matchShopName = new StringBuilder();
    if (!StringUtils.isEmpty(storeName) && !StringUtils.isEmpty(jddjShopName)) {
      for (int i = 0; i < storeName.length(); i++) {
        if (jddjShopName.contains(String.valueOf(storeName.charAt(i)))) {
          matchShopName.append(storeName.charAt(i));
        }
      }
    }
    int storeNameMatchScore = matchKaName.length() * STORE_NAME_PER_WORD_MATCH_SCORE;
    builder.append(
        "门店名称匹配满分30分-到家名称：" + jddjStore.getShopName() + "，品牌门店名称" + shopQuechao.getName() + ",匹配文字"
            + matchShopName + "；得分：" + storeNameMatchScore + "分;---");
    // 5.详细地址文案 匹配 每匹配上一个字 加5分 上限 30分.
    String brandStoreAddress = shopQuechao.getAddress();
    String jddjShopAddress = jddjStore.getAddress();
    StringBuilder matchShopAddressName = new StringBuilder();
    if (!StringUtils.isEmpty(brandStoreAddress) && !StringUtils.isEmpty(jddjShopAddress)) {
      for (int i = 0; i < brandStoreAddress.length(); i++) {
        if (jddjShopAddress.contains(String.valueOf(brandStoreAddress.charAt(i)))) {
          matchShopAddressName.append(brandStoreAddress.charAt(i));
        }
      }
    }
    int storeAddressMatchScore = matchShopAddressName.length() * STORE_ADDRESS_PER_WORD_MATCH_SCORE;
    builder.append(
        "门店名称匹配满分30分-到家名称：" + jddjStore.getShopName() + "，品牌门店名称" + shopQuechao.getName() + ",匹配文字"
            + matchShopName + "；得分：" + storeAddressMatchScore + "分;---");
    return new StoreMatchScoreVo(
        Math.max(distanceScore, 0) + Math.min(kaNameMatchScore, 40)
            + venderGroupMatchScore + Math.min(storeNameMatchScore, 30) +
            Math.min(storeAddressMatchScore, 30),
        builder.toString());
  }

}